#include "radio_station.h"

OPEN_JLIB_NS


u64 RadioStation::subscribe (const std::string& channel, func_t listener) {
  auto& listeners = _channels[channel];
  auto id = _seed++;
  listeners.emplace(id, std::move(listener));
  return id;
}

uwl RadioStation::unsubscribe (const std::string& channel) {
  auto iter = _channels.find(channel);
  if (iter == _channels.end())
    return 0;
  auto& listeners = iter->second;
  auto size = listeners.size();
  listeners.clear();
  return size;
}

uwl RadioStation::unsubscribe (const std::string& channel, u64 id) {
  auto chIter = _channels.find(channel);
  if (chIter == _channels.end())
    return 0;
  auto& listeners = chIter->second;
  auto iter = listeners.find(id);
  if (iter == listeners.end())
    return 0;
  listeners.erase(iter);
  return 1;
}

uwl RadioStation::clear (const std::string& channel) {
  auto chIter = _channels.find(channel);
  if (chIter == _channels.end())
    return 0;
  auto& listeners = chIter->second;
  auto size = listeners.size();
  listeners.clear();
  return size;
}

uwl RadioStation::broadcast (const std::string& channel, void* arg) {
  auto chIter = _channels.find(channel);
  if (chIter == _channels.end())
    return 0;
  auto& listeners = chIter->second;
  uwl reply = 0;
  for (auto& pair : listeners) {
    if (!pair.second)
      continue;
    ++reply;
    if (pair.second(arg))
      break;
  }
  return reply;
}


CLOSE_JLIB_NS

